package com.unis.service.system.impl;

import com.unis.common.util.StrUtil;
import com.unis.common.util.TimeUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.unis.mapper.system.SysPkMapper;
import com.unis.service.system.SysPkService;

/**
 * <pre>
 * @see SysPkService
 * </pre>
 *
 * @author xuk
 * @version 1.0
 * @since 2018-12-28
 */
@Service("sysPkService")
public class SysPkServiceImpl implements SysPkService {
	private static final Logger logger = LoggerFactory.getLogger(SysPkServiceImpl.class);
    @Autowired
    private SysPkMapper sysPkMapper;

	/**
	 * @see SysPkService#getPrimaryKey(String, String, String)
	 * @param seqName sequence名
	 * @param dwdm 单位
	 * @param prefix 前缀 the prefix length  between 1 and 3
	 * @return
	 * @throws Exception
	 */
	@Override
	public String getPrimaryKey(@Param("seqName")String seqName, @Param("dwdm")String dwdm, @Param("prefix")String prefix) throws Exception {
		String pk = null;
		StringBuilder sb = new StringBuilder();
		//验证参数
		//前缀
		if (StringUtils.isNotBlank(prefix) && prefix.trim().length()>=1 && prefix.trim().length()<=3){
			sb.append(prefix.toUpperCase().trim());
		}else {
			return pk;
		}
		//单位
		if(StringUtils.isNotBlank(dwdm) && dwdm.trim().length()==12){
			sb.append(dwdm.trim());
		}else {
			return pk;
		}
		//时间
		String strDate = TimeUtil.getNow("yyyyMMdd");
		sb.append(strDate);
		//序列
		String seqNum = sysPkMapper.getPrimaryKey(seqName);
		if (StringUtils.isNotBlank(seqNum)){
			if (seqNum.length()<8){
				String seqNvl = "";
				for (int i=seqNum.length();i<8;i++){
					seqNvl+="0";
				}
				seqNvl+= seqNum;
				sb.append(seqNvl);
			}else if (seqNum.length()==8){
				sb.append(seqNum);
			}else if (seqNum.length()>8){
				sb.append(seqNum.substring(seqNum.length()-8));
			}else {
				return pk;
			}
		}else{
			return  pk;
		}
		//随机数
		if (sb.toString().trim().length()<32){
			sb.append(StrUtil.getFixLenthString(32-sb.toString().trim().length()));
		}else {
			return pk;
		}
		pk = sb.toString();
		return pk;
	}

	/**
	 * @see SysPkService#getDbDate()
	 * @return
	 */
	@Override
	public String getDbDate() {
		return sysPkMapper.getDbDate();
	}

}
